package com.jlastu.znb.adapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.jlastu.znb.R;
import com.jlastu.znb.entity.Goods;
import com.jlastu.znb.entity.Photo;

import java.util.List;

public class SalesListAdapter extends RecyclerView.Adapter<SalesListAdapter.ViewHolder> {

   private List<Goods> mList;

   public SalesListAdapter(List<Goods> list) {
      mList = list;
   }

   public void updateData(List<Goods> list) {
      mList.clear();
      mList.addAll(list);
      notifyDataSetChanged();
   }

   @NonNull
   @Override
   public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sales_item, parent, false);
      return new ViewHolder(view);
   }

   @Override
   public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
      Goods goods = mList.get(position);

      // 假设Goods类有getPhotoResId()方法返回图片资源ID
      // holder.goodsPhoto.setImageResource(goods.getPhotoResId());

      // 设置商品名称
      holder.goodsName.setText(goods.getName());

      // 设置商品价格，格式化为两位小数并添加货币符号
      holder.goodsPrice.setText(String.format("¥ %.2f", goods.getPrice()));

      // 设置商品单位，假设单位是字符串
      holder.goodsUnit.setText("/ " + goods.getUnit());
      holder.goodsAddress.setText(goods.getAddress());
      List<Photo> photoList = goods.getPhotoList();
      if (photoList != null && photoList.size() > 0) {
         byte[] byteArray = photoList.get(0).getData();
         Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
         holder.goodsPhoto.setImageBitmap(bitmap);
      } else {
         holder.goodsPhoto.setImageResource(R.mipmap.ic_launcher);
      }
   }


   @Override
   public int getItemCount() {
      return mList != null ? mList.size() : 0;
   }

   public static class ViewHolder extends RecyclerView.ViewHolder {
      ImageView goodsPhoto;
      TextView goodsName;
      TextView goodsPrice;
      TextView goodsUnit;
      TextView goodsAddress;

      public ViewHolder(@NonNull View itemView) {
         super(itemView);
         goodsPhoto = itemView.findViewById(R.id.goods_photo);
         goodsName = itemView.findViewById(R.id.goods_name);
         goodsPrice = itemView.findViewById(R.id.goods_price);
         goodsUnit = itemView.findViewById(R.id.goods_unit);
         goodsAddress = itemView.findViewById(R.id.goods_address);
      }
   }
}